package com.xoa.service.crm.impl;


import com.xoa.dao.crm.OrderMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.Order;
import com.xoa.model.crm.OrderExample;
import com.xoa.model.crm.Product;
import com.xoa.model.users.Users;
import com.xoa.service.crm.OrderService;
import com.xoa.util.*;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qiyang on 2019/6/3.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Resource
    private UsersMapper usersMapper;

    /**
     * 查询所有
     * @param page
     * @param pageSize
     * @param useFlag
     * @param map
     * @return
     */
    @Override
    public List<Order> findAll(Integer page, Integer pageSize, Boolean useFlag, Map map) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        List<Order> orders = orderMapper.selectByCondition(map);
        ArrayList<Order> list = new ArrayList<>();
        for (Order o :orders) {
            String creator = o.getCreator();
            String username = usersMapper.getUsernameByUserId(creator);
            o.setCreator(username);
            list.add(o);
        }
        return list;
    }

    /**
     * 添加订单
     * @param order
     * @return
     */
    @Override
    public int addOrder(Order order) {
        //订单编号
        String number="";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        String format = dateFormat.format(date);

        Order order1 = orderMapper.selectNo();
        Integer idNum = 0;

        if (order1!=null) {
            Integer orderId = order1.getOrderId();
            idNum = orderId+1;
            String isNumStr = idNum+"";

            if(isNumStr.length() == 1){
                number = "00000"+isNumStr;
            }else if (isNumStr.length() == 2){
                number = "0000"+isNumStr;
            }else if (isNumStr.length() == 3){
                number = "000"+isNumStr;
            }else if (isNumStr.length() == 4){
                number = "00"+isNumStr;
            }else if (isNumStr.length() == 5){
                number = "0"+isNumStr;
            }else if (isNumStr.length() == 6){
                number = isNumStr;
            }
        }else {
            number = "000001";
        }
        String str="O"+format+number;
        order.setOrderNo(str);
        //创建时间
        order.setCreateTime(date);
        //获取登录用户
        HttpServletRequest request= ((ServletRequestAttributes)(RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie  = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users=  SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionCookie);
        //创建人
        order.setCreator(users.getUserId());
        return orderMapper.insertSelective(order);
    }


    /**
     * 删除订单
     */
    @Override
    public int deleteByPrimaryKey(Integer orderId) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        //根据id查询对象
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //删除时间
        order.setDeleteTime(new Date());
        //删除人
        order.setDeleteUser(users.getUserId());
        //删除状态
        order.setIsDeleted(Byte.valueOf("1"));
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 编辑回显订单数据
     */
    @Override
    public Order selectByPrimaryKey(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Users userId = usersMapper.getUserId(order.getCreator());
        order.setCreator(userId.getUserName());

        return order;
    }

    /**
     * 编辑订单
     */
    @Override
    public int updateByPrimaryKey(Order order) {

        return orderMapper.updateByPrimaryKeySelective(order);
    }

    /*
      * 导出
      * */
    @Override
    public ToJson<Order> orderExport(HttpServletRequest request, HttpServletResponse response) {
        ToJson<Order> json = new ToJson<>();

        try {
            OrderExample example=new OrderExample();
            List<Order> orderList= orderMapper.selectByExample(example);
            List<Order> orderList1=new ArrayList<>();
            for (Order order : orderList) {
                if (order.getIsDeleted()==0){
                    //订单状态
                    Byte status = order.getStatus();
                    if (status==0){
                       order.setStatusStr("下单");
                    }else if(status==1){
                        order.setStatusStr("发货");
                    }else if (status==2){
                        order.setStatusStr("完成");
                    }
                    //订单类型
                    Byte type = order.getType();
                    if (type==0){
                        order.setTypeStr("订货单");
                    }else if (type==1){
                        order.setTypeStr("发货单");
                    }else if (type==2){
                        order.setTypeStr("收货单");
                    }
                    //货币单位
                    String monetaryUnit = order.getMonetaryUnit();
                    if (monetaryUnit.equals("01")){
                        order.setMonetaryUnit("人民币");
                    }else if (monetaryUnit.equals("02")){
                        order.setMonetaryUnit("美元");
                    }else if (monetaryUnit.equals("03")){
                        order.setMonetaryUnit("欧元");
                    }else if (monetaryUnit.equals("04")){
                        order.setMonetaryUnit("英镑");
                    }else if (monetaryUnit.equals("05")){
                        order.setMonetaryUnit("日元");
                    }else if (monetaryUnit.equals("06")){
                        order.setMonetaryUnit("港币");
                    }else if (monetaryUnit.equals("07")){
                        order.setMonetaryUnit("台币");
                    }else if (monetaryUnit.equals("08")){
                        order.setMonetaryUnit("新加坡币");
                    }
                    //付款方式
                    String payWay = order.getPayWay();
                    if (payWay.equals("01")){
                        order.setPayWay("现金");
                    }else if (payWay.equals("02")){
                        order.setPayWay("转账");
                    }else if (payWay.equals("03")){
                        order.setPayWay("支票");
                    }else if (payWay.equals("04")){
                        order.setPayWay("支付宝");
                    }else if (payWay.equals("05")){
                        order.setPayWay("微信");
                    }else if (payWay.equals("06")){
                        order.setPayWay("其他");
                    }
                    Users users = usersMapper.getUserId(order.getCreator());
                    order.setCreator(users.getUserName());
                    order.setCreateTimeStr(DateFormat.getStrDate(order.getCreateTime()));

                    orderList1.add(order);
                }
            }

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("订单表", 9);
            String[] secondTitles = {"订单名称", "订单状态", "订单类型", "订单总金额", "货币单位","付款方式","创建人","创建时间"};


            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

            String[] beanProperty = { "orderName", "statusStr", "typeStr", "total","monetaryUnit","payWay","creator","createTimeStr"};


            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, orderList1, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "订单表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }
    /*
     * 导入
     * */
    @Override
    public ToJson orderImport(HttpServletRequest request, MultipartFile file) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        ToJson json = new ToJson(1,"error");
        //订单编号
        //订单编号
        String number="";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        String format = dateFormat.format(date);

        Order order1 = orderMapper.selectNo();
        Integer idNum = 0;

        if (order1!=null) {
            Integer orderId = order1.getOrderId();
            idNum = orderId+1;
            String isNumStr = idNum+"";

            if(isNumStr.length() == 1){
                number = "00000"+isNumStr;
            }else if (isNumStr.length() == 2){
                number = "0000"+isNumStr;
            }else if (isNumStr.length() == 3){
                number = "000"+isNumStr;
            }else if (isNumStr.length() == 4){
                number = "00"+isNumStr;
            }else if (isNumStr.length() == 5){
                number = "0"+isNumStr;
            }else if (isNumStr.length() == 6){
                number = isNumStr;
            }
        }
        String str="O"+format+number;

        try {
            String fileName = null;
            if (file!=null){
                fileName=file.getOriginalFilename();
            }
            if (fileName!=null&&(fileName.endsWith(".xls")||fileName.endsWith(".xlsx"))){
                int count=0;
                int flag=0;
                Integer uId= (Integer) request.getSession().getAttribute("uid");
                List<Order> list=new ArrayList<>();

                ExcelRead excelRead=new ExcelRead();
                List<Map<String,Object>> readList=excelRead.readExcel(file);
                for (Map<String, Object> map : readList) {
                    if (!"".equals(map.get("订单名称"))&&!"".equals(map.get("订单名称"))){
                        Order order=  new Order();
                        order.setOrderNo(str);
                        order.setOrderName(map.get("订单名称").toString());
                        String  status= map.get("订单状态").toString();
                        String a="";
                        switch (status){
                            case "下单":
                                a = "0";
                                break;
                            case "发货":
                                a = "1";
                                break;
                            case "完成":
                                a = "2";
                                break;
                        }
                        order.setStatus(Byte.valueOf(a));
                        String  type= map.get("订单类型").toString();
                        String  d="";
                        switch (type){
                            case "订货单":
                                d = "0";
                                break;
                            case "发货单":
                                d = "1";
                                break;
                            case "收货单":
                                d = "2";
                                break;
                        }
                        order.setType(Byte.valueOf(d));
                        if(map.get("订单总金额").toString()==null||map.get("订单总金额").toString()==""){
                            Long money = null;
                            order.setTotal(money);
                        }else{
                            order.setTotal(Long.valueOf(map.get("订单总金额").toString()));
                        }
                        String MonetaryUnit= map.get("货币单位").toString();
                        String b="";
                        switch (MonetaryUnit){
                            case "人民币":
                                b = "01";
                                break;
                            case "美元":
                                b = "02";
                                break;
                            case "欧元":
                                b = "03";
                                break;
                            case "英镑":
                                b = "04";
                                break;
                            case "日元":
                                b = "05";
                                break;
                            case "港币":
                                b = "06";
                                break;
                            case "台币":
                                b = "07";
                                break;
                            case "新加坡币":
                                b = "08";
                                break;
                        }
                        order.setType(Byte.valueOf(b));
                        String payWay=map.get("付款方式").toString();
                        String c="";
                        switch (payWay){
                            case "现金":
                                c = "01";
                                break;
                            case "转账":
                                c = "02";
                                break;
                            case "支票":
                                c = "03";
                                break;
                            case "支付宝":
                                c = "04";
                                break;
                            case "微信":
                                c = "05";
                                break;
                            case "其他":
                                c = "06";
                                break;
                        }
                        order.setPayWay(c);
//                        order.setCustomerId(Integer.valueOf(map.get("客户id").toString()));
////                              order.setOrderTime(DateFormat.DateToStr(map.get("下单时间").toString()));
////                              order.setFinishTime(DateFormat.DateToStr(map.get("结单时间").toString()));
//                        order.setContractId(Integer.valueOf(map.get("合同id").toString()));
                        String appr = map.get("审批状态").toString();
                        Byte bytApp = null;
                        switch (appr){
                            case "待审批":
                                bytApp = 0;
                                break;
                            case "已通过":
                                bytApp = 1;
                                break;
                            case "已驳回":
                                bytApp = 2;
                                break;
                        }
                        order.setApprovalStatus(bytApp);
                        order.setApprovalUser(map.get("审批人").toString());
//                        order.setApprovalTime(DateFormat.DateToStr(map.get("审批时间").toString()));
                        order.setApprovalAdvice(map.get("审批意见").toString());
                        order.setRemark(map.get("备注").toString());
                        order.setCreator(users.getUserId());
                        order.setCreateTime(new Date());

                        list.add(order);
                        count++;

                    }
                }
                if (count>0){
                    flag=orderMapper.insertAll(list);
                }
                if (flag>0){
                    json.setFlag(0);
                    json.setMsg("导入成功");
                    json.setTotleNum(count);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}
